We have previously introduced many different types of variables. If we store many variables of the same type together and can use them without having to set the variable name again, we call this collection of data elements an “array”. The data stored in an array must be of the same type (e.g. all Strings).
To declare an array, we place square brackets [ ] after the variable type, enclose the following content in curly brackets, and separate with commas :
//variableType[] variableName = {}
String[] cars = {"Telsa","Benz","BMW"}; //字串陣列內容用雙引號""包起來
int[] num = {12 , 6 , 2001};
char[] character = {'C','H','I'}; //字元陣列內容用單引號''包起來
To read the elements in an array, you access the contents via the index value. Note in particular that the index value for the first element in the array must start from 0, so you need to be careful when accessing the contents.
int[] grade = {65,94,83,100}; //index: 0,1,2,3. grade:65,94,83,100
System.out.println(grade[1]); //Outputs : 94
grade[3] = 54; //改變陣列內元素內容
System.out.println(grade[3]); //Outputs : 54(not 100)
String[] name = {"Chi","Jason","Johnson","Jackson"};
int control,condition;
condition = name.length; //用法 : arrayname.length //condtion = 4
for(control = 0;control < condition ;control++){
System.out.println(name[control]);
}
The concept of a two-dimensional array is a bit difficult to understand at first. To put it simply, we can think of it as two one-dimensional arrays. The declaration method is to add two brackets after the variable type, and the content part will be wrapped in two curly brackets. The brackets and the elements and elements are separated by commas, and the outermost layer is wrapped in another curly bracket.
//variableType[][] variableName = { {} , {} };
int[][] numbers = {{1,2,3},{5,6,7,8}};
System.out.println(numbers[0][1]); //Outputs : 2
System.out.println(numbers[1][0]); //Outputs : 5
int[][] grade = {{54,26,89,67,71},{66,34,54,98}};
grade.length -> 有幾個一維陣列 //outputs 2
grade[i].length -> 一維陣列中各有幾個元素 //number[0].length ->第一個陣列中有5個元素
//number[1].lenght ->第二個陣列中有4個元素